import pandas as pd  # 导入pandas用于数据处理
import smtplib  # 导入smtplib用于发送邮件
from email.mime.text import MIMEText  # 构建邮件内容
from email.mime.multipart import MIMEMultipart  # 构建带附件的邮件
from email.mime.application import MIMEApplication  # 构建附件
import os  # 文件操作

# 1. 读取Excel数据并汇总
excel_file = 'data.xlsx'  # 假设有一个Excel文件
try:
    df = pd.read_excel(excel_file)  # 读取Excel文件
    summary = df.describe()  # 生成数据汇总（统计信息）
    summary_file = 'summary.xlsx'
    summary.to_excel(summary_file)  # 保存汇总结果为新的Excel
    print('数据汇总已生成。')
except Exception as e:
    print(f'Excel处理失败：{e}')
    summary_file = None

# 2. 发送邮件（需配置邮箱信息）
# 请根据实际情况填写以下信息
mail_host = 'smtp.example.com'  # SMTP服务器
mail_user = 'your_email@example.com'  # 发件人邮箱
mail_pass = 'your_password'  # 邮箱密码或授权码
mail_to = 'receiver@example.com'  # 收件人邮箱

if summary_file and os.path.exists(summary_file):
    try:
        msg = MIMEMultipart()
        msg['Subject'] = 'Excel数据汇总报告'
        msg['From'] = mail_user
        msg['To'] = mail_to
        # 邮件正文
        msg.attach(MIMEText('请查收附件中的Excel数据汇总报告。', 'plain', 'utf-8'))
        # 添加附件
        with open(summary_file, 'rb') as f:
            part = MIMEApplication(f.read(), Name=summary_file)
            part['Content-Disposition'] = f'attachment; filename="{summary_file}"'
            msg.attach(part)
        # 连接SMTP服务器并发送邮件
        server = smtplib.SMTP_SSL(mail_host, 465)
        server.login(mail_user, mail_pass)
        server.sendmail(mail_user, [mail_to], msg.as_string())
        server.quit()
        print('邮件发送成功。')
    except Exception as e:
        print(f'邮件发送失败：{e}')
else:
    print('未生成汇总文件，无法发送邮件。') 